package magnus.minimap;

import java.util.ArrayList;
import java.util.List;

import magnus.minimap.Minimap.MinimapHandler;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;


public class MinimapService extends Service {
	public static final int NEW_POSITION_DATA_AVAILABLE = 1;
	private MinimapHandler minimaphandler;
	private ServiceHandler servicehandler;
	private Location currentlocation;
	private Team team;
	private SharedPreferences preferences;
	private int counter = 0;
	
	public MinimapService(MinimapHandler minimaphandler, SharedPreferences preferences) {
		this.minimaphandler = minimaphandler;
		this.preferences = preferences;
		team = new Team(-1); // initialize team with -1, since this implies unknown value
		startservice();
	}

	public void onCreate() {super.onCreate();}
	
	public void startservice() {
		// Start servicetimer
		servicehandler = new ServiceHandler();
		servicehandler.post(mTimerTask);
	}
	
	public ServiceHandler getServiceHandler() {return servicehandler;}
    
	public class ServiceHandler extends Handler {
		public final int TIMER_PING = 0;
		public final int TIMER_STOP = 1;
		public final int USER_NOT_REGISTERED = 2;
		public final int NEW_SERVER_DATA_AVAILABLE = 3;
		public final int NEW_POSITION_DATA_AVAILABLE = 4;
		public final int PREFERENCES_CHANGED = 5;
		public void handleMessage(Message message) {
			switch (message.what) {
			case PREFERENCES_CHANGED: {
				team = new Team(-1); // just reset our team-status
				break;
			}
			case NEW_POSITION_DATA_AVAILABLE: {
				currentlocation = (Location) message.obj;
	            //String a = "mode=insert&id_friend=0&pos_x="+ ((Location)message.obj).getLatitude() + "&pos_y="+((Location)message.obj).getLongitude();
	            Handler connectionhandler = new Handler() {
	            	public void handleMessage(Message msg) {
	            		switch (msg.what) {
	            		case Connection.DONE: {
	            			if (((String)msg.obj).contains("-3")) {
	            				servicehandler.sendMessage(Message.obtain(servicehandler, servicehandler.USER_NOT_REGISTERED,msg.obj));
	            			}
	            			//minimaphandler.sendMessage(Message.obtain(minimaphandler, minimaphandler._TOAST_MESSAGE,"server replied:" + (String)msg.obj));
	            			break;
	            		}
	            		}
	            	}
	            };
				List<NameValuePair> postdata = new ArrayList<NameValuePair>(2);
				postdata.add(new BasicNameValuePair("mode", "insert"));
				postdata.add(new BasicNameValuePair("t_id", Integer.toString(team.get_t_id())));
				postdata.add(new BasicNameValuePair("f_id", Integer.toString(team.getFriendId(0)))); //Id 0 is always ourselves
				postdata.add(new BasicNameValuePair("latitude", Double.toString(((Location)message.obj).getLatitude())));
				postdata.add(new BasicNameValuePair("longitude", Double.toString(((Location)message.obj).getLongitude())));
				//minimaphandler.sendMessage(Message.obtain(minimaphandler, minimaphandler.DEBUG_TEXTVIEW_SET,"query:" + postdata.toString()));
	    		new Connection(connectionhandler).post("http://vindar.se/sql/index.php",postdata);
	    		break;
			}
			case USER_NOT_REGISTERED: {
				//TODO USER_NOT_REGISTERED needs action
				team.addFriend(-1,currentlocation); // add team member zero (that is, ourselves)
				Handler connectionhandler = new Handler() {
					public void handleMessage(Message msg) {
						switch (msg.what) {
						case Connection.DONE: {
							if (((String)msg.obj).startsWith("-")) {
								// API returned error. what now?
								minimaphandler.sendMessage(Message.obtain(minimaphandler, minimaphandler.DEBUG_TOAST_MESSAGE,"usr reg probs"+(String) msg.obj));
							} else {
								// API registered user successfully. what now? 
								team.newRegistration((String)msg.obj);
	            				servicehandler.sendMessage(Message.obtain(servicehandler, servicehandler.NEW_POSITION_DATA_AVAILABLE,currentlocation));
							}
						}
						}
					}
				};
				List<NameValuePair> postdata = new ArrayList<NameValuePair>(2);
				postdata.add(new BasicNameValuePair("mode", "register"));
				postdata.add(new BasicNameValuePair("name", preferences.getString("name","Magnus")));
				postdata.add(new BasicNameValuePair("team", preferences.getString("team","superheroes")));
				postdata.add(new BasicNameValuePair("key", preferences.getString("key","withfruit")));
	    		new Connection(connectionhandler).post("http://vindar.se/sql/index.php",postdata);
				break;
			}
			case TIMER_PING: {
				//minimaphandler.sendMessage(Message.obtain(minimaphandler, minimaphandler.DEBUG_TOAST_MESSAGE,(String) message.obj));
				Handler connection = new Handler () {public void handleMessage(Message servermessage) {switch (servermessage.what) {
				case Connection.DONE: {servicehandler.sendMessage(Message.obtain(servicehandler, servicehandler.NEW_SERVER_DATA_AVAILABLE,(String) servermessage.obj));break;}
				case Connection.ERROR: {minimaphandler.sendMessage(Message.obtain(minimaphandler, minimaphandler.DEBUG_TOAST_MESSAGE,"Connection Problems"));break;}
				}}};
				List<NameValuePair> postdata = new ArrayList<NameValuePair>(2);
				postdata.add(new BasicNameValuePair("mode", "team"));
				postdata.add(new BasicNameValuePair("team", Integer.toString(team.get_t_id())));
				postdata.add(new BasicNameValuePair("key", preferences.getString("key","withfruit")));
				new Connection(connection).post("http://vindar.se/sql/index.php",postdata);
				counter = (counter+1)%10;
				if (counter>9) {new Connection().get("http://vindar.se/sql/index.php?mode=clear");}
				break;
			}
			case NEW_SERVER_DATA_AVAILABLE: {
				//TODO: implement what to do when server data avail.
				//minimaphandler.sendMessage(Message.obtain(minimaphandler, minimaphandler.DEBUG_TEXTVIEW_SET,"server:"+(String)message.obj));
				team.addFriends((String)message.obj);
				minimaphandler.sendMessage(Message.obtain(minimaphandler, minimaphandler.PLOT_LOCATIONS_REQUEST,team.getFriends()));
				break;
			}
			case TIMER_STOP: {servicehandler.removeCallbacks(mTimerTask);break;}
			}//Switch
		}
    }
	private Runnable mTimerTask = new Runnable() {
		   public void run() {
			   servicehandler.sendMessage(Message.obtain(servicehandler, servicehandler.TIMER_PING, "one lap has passed"));
		       servicehandler.postDelayed(mTimerTask, 6000);
		   }
		};

	public int isErrorMessage (String message) {return 0;}
	
	@Override
	public IBinder onBind(Intent arg0) {return null;}
}

